import React from 'react'
import { Result, Button } from 'antd'

interface Props {
  children: React.ReactNode
  fallback?: React.ReactNode
}

interface State {
  hasError: boolean
  error?: Error
}

class ErrorBoundary extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = { hasError: false }
  }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error }
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('Error caught by boundary:', error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        <Result
          status="error"
          title="页面出错了"
          subTitle={this.state.error?.message}
          extra={[
            <Button 
              key="refresh"
              type="primary" 
              onClick={() => window.location.reload()}
            >
              刷新页面
            </Button>
          ]}
        />
      )
    }

    return this.props.children
  }
}

export default ErrorBoundary 